import window from '@ohos.window';
import emitter from '@ohos.events.emitter';
import HashMap from '@ohos.util.HashMap';

let eventIdMap: HashMap<string, number> = new HashMap();
let lastEventId:number=1

export class WTR{

  static getEventId(key:string){
    if(!eventIdMap.hasKey(key)){
      eventIdMap.set(key,lastEventId++)
    }
    return eventIdMap.get(key)
  }

  //应用内通信
  static on(key:string,callback:(data:{ [key: string]: any; })=>void){
    emitter.on({eventId:this.getEventId(key)},(eventData: emitter.EventData)=>{
      callback(eventData.data)
    })
  }
  static off(key:string){
    emitter.off(this.getEventId(key))
  }
  static emit(key:string,data:{ [key: string]: any; }){
    emitter.emit({eventId:this.getEventId(key)},{data:data})
  }

  /*
    mainWindow
    需要设置globalThis.mainWindow
    onWindowStageCreate(windowStage: window.WindowStage) {
      windowStage.loadContent('pages/Index', (err, data) => {
          windowStage.getMainWindow((_,data) => {
            globalThis.mainWindow=data
          })
      });
    }
   */
  static mainWindow():window.Window|null{
    if(globalThis.mainWindow){
      return globalThis.mainWindow
    }
    return null
  }
  static windowWidth():number|null{
    return (WTR.mainWindow())?.getWindowProperties().windowRect.width
  }
  static windowHeight():number|null{
    return (WTR.mainWindow())?.getWindowProperties().windowRect.height
  }

  static randomColor(){
    return `rgb(${(255*Math.random()).toFixed(0)},${(255*Math.random()).toFixed(0)},${(255*Math.random()).toFixed(0)})`
  }



}